package com.lxp.base.net.builder;

import android.text.TextUtils;


import com.lxp.base.net.self.BaseCallBack;
import com.lxp.base.net.self.IBaseHttp;

import java.io.File;
import java.util.Map;

/**
 * Created by lxp on 2017/6/4.
 */

public class GetBuilder extends BaseParamBuilder<GetBuilder> {

    @Override
    public void send(BaseCallBack callBack) {
        try {
            if (TextUtils.isEmpty(mUrl)) {
                throw new IllegalArgumentException("url can not be null !");
            }
            if (null != mParams && !mParams.isEmpty()) {
                mUrl = appendParams(mUrl, mParams);
            }
            if (null != mHeaders && !mHeaders.isEmpty()) {
                mHttp.appendHeaders(mHeaders);
            }
            mHttp.setUrl(mUrl)
                    .setTag(mTag)
                    .isCache(isCache, mCacheTime)
                    .get(callBack);
        } catch (Exception e) {
            callBack.isFail(e);
        }
    }

    public GetBuilder(IBaseHttp mHttp) {
        super(mHttp);
    }

    /**
     * 讲URL和参数 拼接成完整的
     *
     * @param url
     * @param params
     * @return
     */
    private String appendParams(String url, Map<String, Object> params) {
        StringBuilder sb = new StringBuilder();
        sb.append(url + "?");
        if (params != null && !params.isEmpty()) {
            Object obj = null;
            for (String key : params.keySet()) {
                obj = params.get(key);
                if (null != obj && (!(obj instanceof File))) {
                    sb.append(key).append("=").append(obj.toString()).append("&");
                }
            }
        }
        sb = sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }
}
